VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "Email"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
'Send Email
'note: First modify class_initalize to set form address and email server config
'author: jimy.jiang

'demo:
'Dim e As email
'Set e = New email
'e.Send "jimy.jiang@nirvana-info.com", "test", "test content"
'e.Send "jimy.jiang@nirvana-info.com", "test", "test content", "d:\sort.xsl"

Const configurePrex As String = "http://schemas.microsoft.com/cdo/configuration/"
Const smtpTimeout As Integer = 500

Private instance As Variant
Private fromEmail As String
Private smtpServer As String
Private smtpServerPort As Integer
Private loginUser As String
Private loginPassword As String

Private Sub Class_Initialize()
    Set instance = CreateObject("CDO.Message")
    'initalize form address and email server config
    SetFrom "jimy.jiang@nirvana-info.com", "smtp.gmail.com", 465, "jimy.jiang@nirvana-info.com", "xxxxxxxx"
End Sub

Private Sub Class_Terminate()
    Set instance = Nothing
End Sub

Public Sub SetFrom(email As String, server As String, serverPort As Integer, username As String, password As String)
    fromEmail = email
    smtpServer = server
    smtpServerPort = serverPort
    loginUser = username
    loginPassword = password
    Configuration
End Sub

Private Sub Configuration()
    instance.From = fromEmail
    
    instance.Configuration.Fields.Item(configurePrex & "smtpserver") = smtpServer
    instance.Configuration.Fields.Item(configurePrex & "smtpserverport") = smtpServerPort
    instance.Configuration.Fields.Item(configurePrex & "sendusing") = 2
    instance.Configuration.Fields.Item(configurePrex & "smtpauthenticate") = 1
    instance.Configuration.Fields.Item(configurePrex & "sendusername") = loginUser
    instance.Configuration.Fields.Item(configurePrex & "sendpassword") = loginPassword
    instance.Configuration.Fields.Item(configurePrex & "smtpusessl") = 1
    instance.Configuration.Fields.Item(configurePrex & "smtpconnectiontimeout") = smtpTimeout
    instance.Configuration.Fields.Update
End Sub
Public Function Send(toEmail As String, subject As String, body As String, Optional attachment As String) As Boolean
    On Error GoTo failure
    Send = False
    instance.to = toEmail
    instance.subject = subject
    
    instance.HtmlBody = body
    If (attachment <> "") Then
        instance.AddAttachment attachment
    End If

    instance.Send
    Send = True
failure:
End Function
